package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.LoginUser;
import com.platform.dao.ApiRemitMapper;
import com.platform.dao.ApiUserMapper;
import com.platform.entity.RemitVo;
import com.platform.entity.SysParameterVo;
import com.platform.entity.UserAccountVo;
import com.platform.entity.UserVo;
import com.platform.service.ApiRemitService;
import com.platform.service.ApiSysParameterService;
import com.platform.service.ApiUserAccountService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.util.wechat.WechatUtil;
import com.platform.utils.*;
import com.platform.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作者: @zhangzehao <br>
 * 时间: 2018-07-21 08:32<br>
 * 描述: 转账控制表 <br>
 */
@Api(tags = "账户余额管理")
@RestController
@RequestMapping("/api/remit")
public class ApiRemitController extends ApiBaseAction {
    @Autowired
    private ApiRemitService remitService;
    @Autowired
    private ApiSysParameterService sysParameterService;
    @Autowired
    private ApiRemitMapper remitDao;
    @Autowired
    private ApiUserMapper userDao;
    @Autowired
    private ApiUserAccountService userAccountService;
    /**
     * 提交提现申请
     */
    @ApiOperation(value = "提交提现申请")
    @RequestMapping("submit")
    @Transactional
    public Object submit(@LoginUser UserVo loginUser) {
        //RemitVo remitVo = remitService.submit(getJsonRequest(),loginUser);
        Map<String, Object> resultObj = new HashMap<String, Object>();
        try{
            String remit_fee = getJsonRequest().getString("remit_fee");
            Assert.isBlank(remit_fee, "金额不能为空");
            BigDecimal remit_fees = new BigDecimal(remit_fee);
            UserVo userVo = userDao.queryObject(loginUser.getUserId());
            if(remit_fees.compareTo(userVo.getBalance_fee()) == 1){
                throw new RRException("提取金额不能超过当前账户总额");
            }
            RemitVo remitVo = new RemitVo();
            remitVo.setNideshop_user(loginUser.getUserId());
            remitVo.setApply_time(new Date());
            remitVo.setRemit_fee(remit_fees);
            remitVo.setRemit_type(0);
            remitVo.setRemit_status(0);
            remitDao.save(remitVo);
            if(null == remitVo.getId()){
                throw new RRException("提款失败，请重试");
            }

            Map<Object, Object> parame = new TreeMap<Object, Object>();
            parame.put("mch_appid", ResourceUtil.getConfigByName("wx.appId"));
            parame.put("mch_id", ResourceUtil.getConfigByName("wx.mchId"));
            String randomStr = CharUtil.getRandomNum(18).toUpperCase();
            parame.put("nonce_str", randomStr);
            parame.put("partner_trade_no", remitVo.getId());
            parame.put("openid", loginUser.getWeixin_openid());
            parame.put("check_name", "NO_CHECK");
            parame.put("amount", remitVo.getRemit_fee().multiply(new BigDecimal(100)).intValue());
            parame.put("desc", "哈哈农匠会员提现");
            parame.put("spbill_create_ip", getClientIp());
            String sign = WechatUtil.arraySign(parame, ResourceUtil.getConfigByName("wx.paySignKey"));
            parame.put("sign", sign);
            String xml = MapUtils.convertMap2Xml(parame);
            logger.info("xml:" + xml);
            Map<String, Object> resultUn = XmlUtil.xmlStrToMap(WechatUtil.requestOnce(ResourceUtil.getConfigByName("wx.remitUrl"), xml));
            String return_code = MapUtils.getString("return_code", resultUn);
            String return_msg = MapUtils.getString("return_msg", resultUn);
            if (return_code.equalsIgnoreCase("FAIL")) {
                throw new RRException("提取失败"+ return_msg);
            } else if (return_code.equalsIgnoreCase("SUCCESS")) {
                // 返回数据
                String result_code = MapUtils.getString("result_code", resultUn);
                String err_code_des = MapUtils.getString("err_code_des", resultUn);
                if (result_code.equalsIgnoreCase("FAIL")) {
                    throw new RRException("提取失败"+ return_msg);
                } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                    userVo.setBalance_fee(userVo.getBalance_fee().subtract(remit_fees));
                    userDao.update(userVo);
                    remitVo.setRemit_time(new Date());
                    remitVo.setRemit_status(2);
                    remitService.updateRemit(remitVo);
                    resultObj.put("errno", 0);
                    resultObj.put("errmsg", "操作成功");
                    return resultObj;
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new RRException("提款失败"+e.getMessage());
        }
        resultObj.put("errno", 1);
        resultObj.put("errmsg", "提现失败");
        return resultObj;
    }

    /**
     * 查询转账日志
     */
    @ApiOperation(value = "查询转账日志")
    @RequestMapping(value = "getRemitLog")
    public Object getRemitLog(@LoginUser UserVo loginUser) {
        try{
            JSONObject jsonParams = getJsonRequest();
            int page = jsonParams.getInteger("page");
            int size = jsonParams.getInteger("size");
            System.out.println("=======page=============:"+page);
            Map params = new HashMap();
            params.put("nideshop_user", loginUser.getUserId());
            params.put("page", page);
            params.put("limit", size);
            params.put("sidx", "apply_time");
            params.put("order", "desc");
            //查询列表数据
            Query query = new Query(params);
            List<RemitVo> remits = remitService.queryRemitList(query);
            int total = remitService.queryTotal(query);
            ApiPageUtils pageUtil = new ApiPageUtils(remits, total, query.getLimit(), query.getPage());
            return toResponsSuccess(pageUtil);
        }catch(Exception e){
            e.printStackTrace();
            throw new RRException("查询失败"+e.getMessage());
        }
    }

    /**
     * 每日签到
     */
    @ApiOperation(value = "每日签到")
    @RequestMapping("userSign")
    @Transactional
    public Object userSign(@LoginUser UserVo loginUser) {
        if(StringUtils.isNullOrEmpty(loginUser.getBalance_fee())||(loginUser.getBalance_fee().compareTo(new BigDecimal(100))<0)){
            return toResponsFail("需要100以上笑笑购物券才能签到");
        }
        long current = System.currentTimeMillis();
        long zero = current/(1000*3600*24)*(1000*3600*24) - TimeZone.getDefault().getRawOffset();
        if(loginUser.getSign_time()!=null && loginUser.getSign_time().getTime()>=zero){
            return toResponsFail("每天只能签到一次");
        }
        //获取签到规则比例并计算签到积分
        Map sysParameterParam = new HashMap();
        sysParameterParam.put("parameter", "sign_rate");
        List<SysParameterVo> sysParameterList = sysParameterService.queryList(sysParameterParam);
        if(sysParameterList == null||sysParameterList.size()!= 1||StringUtils.isNullOrEmpty(sysParameterList.get(0).getParameter_value())){
            return toResponsFail("请联系客服");
        }
        BigDecimal money_base = loginUser.getBalance_fee().divide(new BigDecimal("100"));
        money_base = money_base.setScale(0,BigDecimal.ROUND_DOWN);
        money_base = money_base.multiply(new BigDecimal("100"));
        BigDecimal sign_money = money_base.multiply(new BigDecimal(sysParameterList.get(0).getParameter_value()));
        if(StringUtils.isNullOrEmpty(loginUser.getSign_fee())){
            loginUser.setSign_fee(sign_money);
        }else{
            loginUser.setSign_fee(loginUser.getSign_fee().add(sign_money));
        }
        loginUser.setSign_time(new Date());
        int user_index = userDao.update(loginUser);
        if(user_index!=1){
            return toResponsFail("请稍后重试");
        }
        return toResponsSuccess(loginUser);
    }

    /**
     * 转账
     */
    @ApiOperation(value = "转账")
    @RequestMapping("payment")
    @Transactional
    public Object payment(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        int paymentType = jsonParams.getInteger("paymentType");
        String phone = jsonParams.getString("phone");
        BigDecimal money = jsonParams.getBigDecimal("money");
        if(StringUtils.isNullOrEmpty(paymentType)||paymentType<=0||StringUtils.isNullOrEmpty(phone)||StringUtils.isNullOrEmpty(money)){
            return toResponsFail("请求数据不能为空");
        }
        if(money.compareTo(new BigDecimal(0))<=0){
            return toResponsFail("金额输入格式不正确");
        }
        if(paymentType == 1 && ( StringUtils.isNullOrEmpty(loginUser.getSign_fee())||(loginUser.getSign_fee().compareTo(money)<0))){
            return toResponsFail("账户资金不足");
        }
        if(paymentType == 2 && ( StringUtils.isNullOrEmpty(loginUser.getBalance_fee())||(loginUser.getBalance_fee().compareTo(money)<0))){
            return toResponsFail("账户资金不足");
        }
        if(phone.equals(loginUser.getMobile())){
            return toResponsFail("只允许向他人转账");
        }
        List<UserVo> userVos = userDao.queryByMobile(phone);
        if(userVos == null||userVos.size()!=1){
            return toResponsFail("对方账户不存在或对方账户异常");
        }
        UserVo userVo = userVos.get(0);
        RemitVo remitVo = new RemitVo();
        if(paymentType == 1){
            loginUser.setSign_fee(loginUser.getSign_fee().subtract(money));
            if(StringUtils.isNullOrEmpty(userVo.getSign_fee())){
                userVo.setSign_fee(money);
            }else{
                userVo.setSign_fee(userVo.getSign_fee().add(money));
            }
        }
        if(paymentType == 2){
            loginUser.setBalance_fee(loginUser.getBalance_fee().subtract(money));
            if(StringUtils.isNullOrEmpty(userVo.getBalance_fee())){
                userVo.setBalance_fee(money);
            }else{
                userVo.setBalance_fee(userVo.getBalance_fee().add(money));
            }
        }
        remitVo.setSys_user(loginUser.getUserId());
        remitVo.setNideshop_user(userVo.getUserId());
        remitVo.setApply_time(new Date());
        remitVo.setRemit_time(new Date());
        remitVo.setRemit_fee(money);
        remitVo.setRemit_type(paymentType);
        remitVo.setRemit_status(2);

        userDao.update(loginUser);
        userDao.update(userVo);
        remitDao.save(remitVo);
        return toResponsSuccess(loginUser);
    }

    /**
     * 商家兑换购物劵
     */
    @ApiOperation(value = "商家兑换购物劵")
    @RequestMapping("drawings")
    @Transactional
    public Object drawings(@LoginUser UserVo loginUser){
        JSONObject jsonParams = getJsonRequest();
        int remitType = jsonParams.getInteger("remitType");
        Long accountId = jsonParams.getLong("accountId");
        BigDecimal remitFee = jsonParams.getBigDecimal("remitFee");
        if(StringUtils.isNullOrEmpty(remitType)||remitType<=0||StringUtils.isNullOrEmpty(accountId)||StringUtils.isNullOrEmpty(remitFee)){
            return toResponsFail("请求数据不能为空");
        }
        if(remitFee.compareTo(new BigDecimal(0))<=0){
            return toResponsFail("金额输入格式不正确");
        }
        if(remitType == 1 && ( StringUtils.isNullOrEmpty(loginUser.getSign_fee())||(loginUser.getSign_fee().compareTo(remitFee)<0))){
            return toResponsFail("账户资金不足");
        }
        if(remitType == 2 && ( StringUtils.isNullOrEmpty(loginUser.getBalance_fee())||(loginUser.getBalance_fee().compareTo(remitFee)<0))){
            return toResponsFail("账户资金不足");
        }
        UserAccountVo userAccountVo = userAccountService.queryObject(accountId);
        if(userAccountVo==null){
            return toResponsFail("资金账户异常请核查");
        }
        UserVo userVo = userDao.queryObject(1);
        if(userVo == null){
            return toResponsFail("笑笑宝账户异常,请联系服务人员");
        }
        RemitVo remitVo = new RemitVo();
        if(remitType == 1){
            loginUser.setSign_fee(loginUser.getSign_fee().subtract(remitFee));
            if(!StringUtils.isNullOrEmpty(userVo.getSign_fee())){
                userVo.setSign_fee(userVo.getSign_fee().add(remitFee));
            }else{
                userVo.setSign_fee(remitFee);
            }
        }
        if(remitType == 2){
            loginUser.setBalance_fee(loginUser.getBalance_fee().subtract(remitFee));
            if(!StringUtils.isNullOrEmpty(userVo.getBalance_fee())){
                userVo.setBalance_fee(userVo.getBalance_fee().add(remitFee));
            }else{
                userVo.setBalance_fee(remitFee);
            }
        }
        remitVo.setSys_user(loginUser.getUserId());
        remitVo.setNideshop_user(userVo.getUserId());
        remitVo.setApply_time(new Date());
        remitVo.setRemit_fee(remitFee);
        remitVo.setRemit_type(remitType);
        remitVo.setRemit_status(0);
        remitVo.setAccount_id(accountId);

        userDao.update(loginUser);
        userDao.update(userVo);
        remitDao.save(remitVo);
        return toResponsSuccess(loginUser);
    }

    /**
     * 消费者购买购物劵
     */
    @ApiOperation(value = "消费者购买购物劵")
    @RequestMapping("purchase")
    @Transactional
    public Object purchase(@LoginUser UserVo loginUser){
        JSONObject jsonParams = getJsonRequest();
        BigDecimal remitFee = jsonParams.getBigDecimal("remitFee");
        if(StringUtils.isNullOrEmpty(remitFee)){
            return toResponsFail("请求数据不能为空");
        }
        if(remitFee.compareTo(new BigDecimal(0))<=0){
            return toResponsFail("金额输入格式不正确");
        }
        UserVo xiaoxiaouserVo = userDao.queryObject(1);
        if(xiaoxiaouserVo == null){
            return toResponsFail("笑笑宝账户异常,请联系服务人员");
        }
        RemitVo remitVo = new RemitVo();

        remitVo.setSys_user(xiaoxiaouserVo.getUserId());
        remitVo.setNideshop_user(loginUser.getUserId());
        remitVo.setApply_time(new Date());
        remitVo.setRemit_fee(remitFee);
        remitVo.setRemit_type(2);
        remitVo.setRemit_status(0);

        remitDao.save(remitVo);
        return toResponsMsgSuccess("请求成功！请尽快汇款");
    }
}
